package com.wenyu.wenyuyuedu.activity.personage;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.view.Window;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.jingchen.pulltorefresh.PullToRefreshLayout;
import com.jingchen.pulltorefresh.PullableListView;
import com.wenyu.wenyuyuedu.R;
import com.wenyu.wenyuyuedu.activity.LoginActivity;
import com.wenyu.wenyuyuedu.activity.homepage.MyAttentionActivity;
import com.wenyu.wenyuyuedu.adapter.personage.MyCollectAdapter;
import com.wenyu.wenyuyuedu.adapter.personage.MyZanAdapter;
import com.wenyu.wenyuyuedu.bean.personage.MyMessagesBean;
import com.wenyu.wenyuyuedu.bean.personage.ReturnMsgBean;
import com.wenyu.wenyuyuedu.global.ApiWrapper;
import com.wenyu.wenyuyuedu.server.personage.MyMessagesServer;
import com.wenyu.wenyuyuedu.server.personage.RemoveMsgServer;
import com.wenyu.wenyuyuedu.server.personage.ReturnMsgServer;
import com.wenyu.wenyuyuedu.utils.AbSharedUtil;
import com.wenyu.wenyuyuedu.utils.MyToast;
import com.wenyu.wenyuyuedu.utils.SharedConstants;
import com.wenyu.wenyuyuedu.utils.StatusBarUtil;

import java.util.ArrayList;
import java.util.List;

import butterknife.ButterKnife;
import butterknife.InjectView;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

import static anetwork.channel.http.NetworkSdkSetting.context;

/*
* 赞
* */
public class MessageZanActivity extends AppCompatActivity implements View.OnClickListener {

    @InjectView(R.id.zan_left)
    ImageView zanLeft;
    @InjectView(R.id.meassage_zan_clear)
    TextView meassageZanClear;
    @InjectView(R.id.message_content_view)
    PullableListView messageContentView;
    @InjectView(R.id.message_refresh_view)
    PullToRefreshLayout messageRefreshView;
    private Intent intent;
    private int page = 1;
    private ListView pullableView;
    private boolean isLoading = false;
    private List<MyMessagesBean.InfoBean> infoAll = new ArrayList<>();
    private List<MyMessagesBean.InfoBean> info;
    private Activity activity;
    private String token;
    private MyZanAdapter adapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_message_zan);
        StatusBarUtil.setStatusBar(MessageZanActivity.this, R.color.white);
        ButterKnife.inject(this);
        activity = this;
        initControl();
        initPullToRefresh();
    }

    /*初始化下拉刷新加载更多*/
    private void initPullToRefresh() {
        pullableView = (ListView) messageRefreshView.getPullableView();
        messageRefreshView.setOnPullListener(new PullToRefreshLayout.OnPullListener() {
            @Override
            public void onRefresh(PullToRefreshLayout pullToRefreshLayout) {
                new Handler() {
                    public void handleMessage(Message msg) {
                        page = 1;
                        isLoading = false;
                        requestData();
                        //千万别忘了告诉控件刷新完毕了
                        messageRefreshView.refreshFinish(PullToRefreshLayout.SUCCEED);
                    }
                }.sendEmptyMessageDelayed(0, 1000);
            }

            @Override
            public void onLoadMore(PullToRefreshLayout pullToRefreshLayout) {
                new Handler() {
                    public void handleMessage(Message msg) {
                        page++;
                        isLoading = true;
                        requestData();

                        //千万别忘了告诉控件刷新完毕了
                        messageRefreshView.refreshFinish(PullToRefreshLayout.SUCCEED);
                    }
                }.sendEmptyMessageDelayed(0, 1000);
            }
        });

    }

    AlertDialog ad;
    private TextView quxiao;
    private TextView queding;

    /*token错误或者已失效*/
    private void showLoginDialog() {
        ad = new AlertDialog.Builder(activity).create();
        ad.show();
        Window window = ad.getWindow();
        window.setContentView(R.layout.dailog_login);
        quxiao = (TextView) window.findViewById(R.id.dialog_login_quxiao);
        queding = (TextView) window.findViewById(R.id.dialog_login_queding);
        quxiao.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ad.dismiss();
                finish();
            }
        });
        queding.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(activity, LoginActivity.class);
                startActivity(intent);
                ad.dismiss();
                finish();
            }
        });
    }

    @Override
    protected void onStart() {
        super.onStart();
        requestData();
    }

    /*获取数据*/
    private void requestData() {
        MyMessagesServer myMessagesServer = ApiWrapper.getInstance().create(MyMessagesServer.class);
        Call<MyMessagesBean> myMessages = myMessagesServer.getMyMessages(token, 3, page);
        myMessages.enqueue(new Callback<MyMessagesBean>() {
            @Override
            public void onResponse(Call<MyMessagesBean> call, Response<MyMessagesBean> response) {
                MyMessagesBean body = response.body();
                if (body != null) {
                    int code = body.getCode();
                    String msg = body.getMsg();
                    if (code == 1) {
                        info = body.getInfo();
                        if (!isLoading) {
                            infoAll.clear();
                            adapter.clear();
                        }
                        infoAll.addAll(info);
                        adapter.addAll(infoAll);
                    } else if (code == 0) {
                        showLoginDialog();
                    } else if (code == 5000) {
                        showLoginDialog();
                    } else if (code == 5300) {
                        MyToast.showToast(activity, "您暂时还没有消息通知", Toast.LENGTH_SHORT);
                    } else if (code == 5301) {
                        MyToast.showToast(activity, "消息通知已全部加载完毕!", Toast.LENGTH_SHORT);
                    }
                }
            }

            @Override
            public void onFailure(Call<MyMessagesBean> call, Throwable t) {
                MyToast.showToast(activity, "网络异常，请稍后重试!", Toast.LENGTH_SHORT);
            }
        });
    }

    /*
 * 初始化控件
 * */
    private void initControl() {
        intent = new Intent();
        token = AbSharedUtil.getString(activity, SharedConstants.USER_TOKEN);
        zanLeft.setOnClickListener(this);
        meassageZanClear.setOnClickListener(this);
        adapter = new MyZanAdapter(activity);
        messageContentView.setAdapter(adapter);
        adapter.setDeleteOnClickLis(new MyCollectAdapter.deleteOnclickListener() {
            @Override
            public void onClick(int position, View view) {
                switch (view.getId()) {
                    /*点击条目*/
                    case R.id.tv:
                        String deleteId = info.get(position).getId();
                        returnMesg(deleteId, position);
                        break;
                    /*点击侧滑的删除*/
                    case R.id.btn_delete:
                        String id = info.get(position).getId();
                        deleteItem(id, position);
                        break;
                }
            }
        });
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            /*返回*/
            case R.id.zan_left:
                finish();
                break;
            /*清空*/
            case R.id.meassage_zan_clear:
                MyToast.showToast(activity, "清空成功", Toast.LENGTH_SHORT);
                break;
        }
    }

    /*判断用户已读未读*/
    private void returnMesg(String deleteId, final int position) {
        ReturnMsgServer returnMsgServer = ApiWrapper.getInstance().create(ReturnMsgServer.class);
        Call<ReturnMsgBean> returnMsg = returnMsgServer.getReturnMsg(token, deleteId);
        returnMsg.enqueue(new Callback<ReturnMsgBean>() {
            @Override
            public void onResponse(Call<ReturnMsgBean> call, Response<ReturnMsgBean> response) {
                ReturnMsgBean body = response.body();
                if (body != null) {
                    int code = body.getCode();
                    if (code == 1) {
                        intent.setClass(activity, MyAttentionActivity.class);
                    /*对应帖子的id*/
                        intent.putExtra("allattentionid", info.get(position).getObject_id());
                    /*对应帖子的圈子的昵称*/
                        intent.putExtra("allattentiontitle", info.get(position).getCircle_title());
                    /*对应发帖人的昵称*/
                        intent.putExtra("allattentionnickname", info.get(position).getPost_publisher_name());
                    /*对应发帖子人的uid*/
                        intent.putExtra("allattentionnicknameuid", info.get(position).getPost_publisher_id());
                        startActivity(intent);
                    } else if (code == 0) {
                        MyToast.showToast(context, "登陆失效，请重新登陆！", Toast.LENGTH_SHORT);
                    } else if (code == 6000) {
                        MyToast.showToast(context, "系统繁忙，请稍后重试！", Toast.LENGTH_SHORT);

                    }
                }
            }

            @Override
            public void onFailure(Call<ReturnMsgBean> call, Throwable t) {
                MyToast.showToast(context, "网络错误，请稍后重试！", Toast.LENGTH_SHORT);
            }
        });
    }


    /*删除条目*/
    private void deleteItem(String id, final int position) {

        RemoveMsgServer removeMsgServer = ApiWrapper.getInstance().create(RemoveMsgServer.class);
        Call<ReturnMsgBean> removeMsg = removeMsgServer.getRemoveMsg(token, id, 1);
        removeMsg.enqueue(new Callback<ReturnMsgBean>() {
            @Override
            public void onResponse(Call<ReturnMsgBean> call, Response<ReturnMsgBean> response) {
                ReturnMsgBean body = response.body();
                if (body != null) {
                    int code = body.getCode();
                    if (code == 1) {
                        adapter.getList().remove(position);
                        adapter.notifyDataSetChanged();
                    } else if (code == 0) {
                        showLoginDialog();
                    } else if (code == 6100) {
                        MyToast.showToast(activity, "系统繁忙，请稍后重试！", Toast.LENGTH_SHORT);
                    }
                }
            }

            @Override
            public void onFailure(Call<ReturnMsgBean> call, Throwable t) {
                MyToast.showToast(activity, "系统繁忙，请稍后重试！", Toast.LENGTH_SHORT);
            }
        });
    }
}
